<template>
  <a-drawer
    title="动作"
    :maskStyle="{background: 'transparent'}"
    :maskClosable="false"
    :visible="dialog"
    width="500"
    @close="cancel"
  >
    <div class="worksheet_trigger_body">
      <div class="worksheet_trigger_form">
        <div class="form_item" v-if="node.stepType === 'SEND_WEBHOOK'">
          <a-radio-group v-model="webhookData.webhookType">
            <a-radio value="defaultRequest">
              发送指定webhook
            </a-radio>
            <a-radio value="customRequest">
              发送自定义webhook
            </a-radio>
          </a-radio-group>
        </div>
        <div class="form_item" v-for="item in schemaInputs" :key="item.id">
          <template v-if="item.customType === 'worksheet'">
            <div class="form_item_title">{{item.title}}</div>
            <a-select v-model="inputs[item.key]" @change="handleSelectWorksheet" optionFilterProp='children' show-search style="width: 100%">
              <a-select-option v-for="item in worksheetList" :key="item.id" :value="item.id">
                {{item.name}}
              </a-select-option>
            </a-select>
          </template>
          <template v-if="inputs.worksheetId && inputs.worksheetId !== '' && item.customType === 'row'">
            <div class="form_item_title">{{item.title}}</div>
            <div v-for="item in fieldList" :key="item.name">
              <workflow-input v-model="formData[item.name]" :field="item" :output="output" v-if="item.dataType === DataType.TEXT || item.dataType === DataType.TEXT_AREA 
              || item.dataType === DataType.RICH_TEXT || item.dataType === DataType.UPLOAD_IMG || item.dataType===DataType.UPLOAD_FILE"></workflow-input>
              <workflow-input-number v-model="formData[item.name]" :field="item" :output="output" v-if="item.dataType === DataType.NUMBER"></workflow-input-number>
              <workflow-selected v-model="formData[item.name]" :field="item" :output="output" v-if="item.dataType === DataType.SELECT || item.dataType === DataType.RADIO"></workflow-selected>
              <workflow-date v-model="formData[item.name]" :field="item" :output="output" v-if="item.dataType === DataType.DATE"></workflow-date>
            </div>
          </template>
          <template v-if="item.customType === 'selectNode'">
            <div class="form_item_title">{{item.title}}</div>
            <a-select v-model="inputs[item.key]" optionFilterProp='children' show-search style="width: 100%">
              <a-select-option v-for="item in output" :key="item.nodeId" :value="item.nodeId">
                {{item.nodeName}}
              </a-select-option>
            </a-select>
          </template>
          <template v-if="item.customType === 'notice'">
            <div class="form_item_title">{{item.title}}</div>
             <workflow-notice v-model="noticeData[item.key]" :noticeData="noticeData.noticeStoreData" @change="handleNoticeChange" :output="output"></workflow-notice>
          </template>
          <template v-if="item.customType === 'userIds'">
            <div class="form_item_title">指定人员</div>
            <user-container v-for="item in userList" :user="item" :key="item.userId" @deleteuser="handleDeleteUser"></user-container>
            <a-button @click="handleAddUser">添加成员</a-button>
          </template>
          <template v-if="item.customType === 'customRequest' && webhookData.webhookType === 'customRequest'">
            <div class="form_item_title">选择数据对象</div>
            <a-select v-model="webhookData.customData.httpMethod" optionFilterProp='children' show-search style="width: 100%">
              <a-select-option value="GET">
                GET
              </a-select-option>
              <a-select-option value="POST">
                POST
              </a-select-option>
            </a-select>
            <div class="form_item_title">发送流程数据对象</div>
            <workflow-notice v-model="webhookData.customData.webhookUrl" :noticeData="webhookData.customData.webhookUrlStoreData" @change="handleWebhookUrlChange" :output="output"></workflow-notice>
            <div class="form_item_title">Headers</div>
            <webhook-headers :headers="webhookData.customData.headers" 
              :output="output"
              title="header"
              @change="webhookHeaderChange"
            >
            </webhook-headers>
            <div class="form_item_title">Body</div>
            <a-radio-group v-model="webhookData.customData.bodyType">
              <a-radio value="kv">
                key-value pairs
              </a-radio>
              <a-radio value="raw">
                raw (application/json)
              </a-radio>
            </a-radio-group>
            <webhook-headers v-if="webhookData.customData.bodyType === 'kv'"
              :headers="webhookData.customData.body.kv" 
              :output="output"
              title="body"
              @change="webhookBodyChange"
            >
            </webhook-headers>
            <workflow-notice v-if="webhookData.customData.bodyType === 'raw'"
              v-model="webhookData.customData.body.raw" 
              :noticeData="webhookData.customData.bodyRowStoreData" 
              @change="handleBodyRowChange" 
              :output="output"
            ></workflow-notice>
          </template>
          <template v-if="item.customType === 'defaultRequest' && webhookData.webhookType === 'defaultRequest'">
            <div class="form_item_title">选择数据对象</div>
            <a-select v-model="webhookData.defaultData.nodeId" optionFilterProp='children' show-search style="width: 100%">
              <a-select-option v-for="outputItem in output" :key="outputItem.nodeId" :value="outputItem.nodeId">
                {{outputItem.nodeName}}
              </a-select-option>
            </a-select>
            <div class="form_item_title">发送流程数据对象</div>
            <workflow-notice v-model="webhookData.defaultData.webhookUrl" :noticeData="webhookData.defaultData.webhookUrlStoreData" @change="handleWebhookUrlChange" :output="output"></workflow-notice>
            <div class="form_item_title">Headers</div>
            <webhook-headers :headers="webhookData.defaultData.headers" 
              :output="output"
              title="header"
              @change="webhookHeaderChange"
            >
            </webhook-headers>
          </template>
        </div>
        <div class="form_item">
          <!-- <template>
            <div class="form_item_title">多人审批时采用的审批方式</div>
            
          <a-radio-group v-model="webhookData.webhookType">
            <a-radio value="defaultRequest">
              发送指定webhook
            </a-radio>
            <a-radio value="customRequest">
              发送自定义webhook
            </a-radio>
          </a-radio-group>
          </template> -->
          <!-- <template>
            <div class="form_item_title">{{item.title}}</div>
            <user-container v-for="item in userList" :user="item" :key="item.userId" @deleteuser="handleDeleteUser"></user-container>
            <a-button @click="handleAddUser">添加成员</a-button>
          </template> -->
        </div>
      </div>
      <div class="worksheet_trigger_foot">
        <a-button type="primary" @click="save">
          保存
        </a-button>
        <a-button @click="cancel">
          取消
        </a-button>
      </div>
    </div>
    <user-modal v-if="showUserModal" :userList="userData" :visible="showUserModal" @ok="addUser" @close="showUserModal = false"></user-modal>
  </a-drawer>
</template>
<script>
import { getUserList } from '@/api/authority'
import {uuid} from "@/utils/utils"
import {getAllWorksheet} from "@/api/app"
import {getWorksheetDetail} from "@/api/worksheet"
import {getNodeOutput} from "@/api/appWorkflow"
import WorkflowDate from "../../workflowDate.vue"
import WorkflowSelected from "../../workflowSelected.vue"
import WorkflowInput from "../../workflowInput.vue"
import WorkflowInputNumber from "../../workflowInputNumber.vue"
import WorkflowNotice from "../../workflowNotice.vue"
import WebhookHeaders from "../../webhookHeader/index"
import UserModal from '../../../../modal/userModal.vue'
import UserContainer from '../../user/index.vue'
import {DataType, FilterType, DateRange} from '@/filterConstant'
export default {
  components: {
    WorkflowInput,
    WorkflowInputNumber,
    WorkflowDate,
    WorkflowSelected,
    UserModal,
    UserContainer,
    WorkflowNotice,
    WebhookHeaders,
  },
  props: {
    dialog: {
      type: Boolean,
      default: false
    },
    node: {
      type: Object,
      default: undefined
    }
  },
  data(){
      return {
        worksheetList: [],
        schemaInputs: [],
        fieldList: [],
        inputs:{},
        formData: {},

        noticeData: {},
        webhookData:{
          webhookType: 'defaultRequest',
          defaultData:{
            headers: [],
            nodeId: '',
            webhookUrl: '',
            webhookUrlStoreData: '',
          },
          customData:{
            headers: [],
            bodyType: 'kv',
            bodyRowStoreData: '',
            body: {
              kv: [
                {
                  uuid: 'first',
                  key:"",
                  value: "",
                  storeValue: ""
                }
              ],
              raw: '',
            },
            httpMethod: 'GET',
            webhookUrl: '',
            webhookUrlStoreData: '',
          },
        },
        approveData:{
          nodeId: '',
          users: [],
          approveMode: '',
          approveSetting: [],
          buttonName:{},
          fieldSetting: {}
        },

        DataType,
        showUserModal: false,
        output: [],
        userList: [],
        userData: [],
      }
  },
  watch: {
    dialog: {
      async handler (val) {
        if(this.dialog){
          let data = await getAllWorksheet(this.appId)
          this.worksheetList = data
          let schemaInputs = this.node?.schema?.inputs || {}
          this.inputs = this.node?.inputs || {}
          if(this.inputs.worksheetId){
            this.handleSelectWorksheet(this.inputs.worksheetId)
          }
          let output = await getNodeOutput({
            automationId: this.id,
            nodeId: this.node.nodeId
          })
          this.output = output
          this.formData = this.inputs.row || {}
          if(this.node.stepType === "SEND_NOTICE"){
            if(this.inputs?.userIds){
              let userIds = this.inputs.userIds.split(',')
              let userList = []
              getUserList().then((res) => {
                  if(res.data && res.data.success){
                    userIds.forEach(u => {
                      for (let i = 0; i < res.data.data.length; i++) {
                          let user = res.data.data[i];
                          if(u === user.userId){
                            userList.push({
                                userId: user.userId,
                                userAlia: user.name,
                            })
                            break
                          }
                      }
                    })
                  }
                  this.userList = userList
              })
            }
            
            this.noticeData = this.inputs
          }
          if(this.node.stepType === "SEND_WEBHOOK"){
            if(this.inputs.defaultRequest){
              this.webhookData.webhookType = 'defaultRequest'
              this.webhookData.defaultData = this.inputs.defaultRequest
            }
            else if(this.inputs.customRequest){
              this.webhookData.webhookType = 'customRequest'
              this.webhookData.customData = this.inputs.customRequest

              if(!this.webhookData.customData.body.kv){
                this.webhookData.customData.body.kv = [{
                  uuid: 'first',
                  key:"",
                  value: "",
                  storeValue: ""
                }]
              }
              if(!this.webhookData.customData.body.raw){
                this.webhookData.customData.body.raw = ''
              }
            }
          }
          this.schemaInputs = schemaInputs.order.map(o => {
            for (const key in schemaInputs.properties) {
              if(key === o){
                return {
                  ...schemaInputs.properties[key],
                  id: uuid(),
                  key
                }
              }
            }
          })
        }
      },
      deep: true,
    },
  },
  methods: {
    webhookBodyChange(value){
      this.webhookData.customData.body.kv = value
    },
    webhookHeaderChange(headers){
      if(this.webhookData.webhookType === 'defaultRequest'){
         this.webhookData.defaultData.headers = headers
      }
      else if(this.webhookData.webhookType === 'customRequest'){
         this.webhookData.customData.headers = headers
      }
    },
    handleWebhookUrlChange(value){
      if(this.webhookData.webhookType === 'defaultRequest'){
         this.webhookData.defaultData.webhookUrlStoreData = value
      }
      else if(this.webhookData.webhookType === 'customRequest'){
         this.webhookData.customData.webhookUrlStoreData = value
      }
    },
    handleBodyRowChange(value){
      this.webhookData.customData.bodyRowStoreData = value
    },
    handleNoticeChange(value){
      this.noticeData.noticeStoreData = value
    },
    handleAddUser(){
      this.showUserModal = true
      getUserList().then((res) => {
          if(res.data && res.data.success){
              let userData = [];
              for (let i = 0; i < res.data.data.length; i++) {
                  let user = res.data.data[i];
                  let flag = false
                  for(let j = 0; j < this.userList.length; j++){
                    let addU = this.userList[j]
                    if(addU.userId === user.userId){
                      flag = true
                      userData.push({
                          userId: user.userId,
                          userAlia: user.name,
                          check: true
                      })
                      break
                    }
                  }
                  if(flag) continue
                  userData.push({
                      userId: user.userId,
                      userAlia: user.name,
                      check: false
                  })
              }
              this.userData = userData
          }
      })
    },
    handleDeleteUser (userId) {
      this.userList = this.userList.filter(u => u.userId !== userId)
    },
    cancel () {
      this.$emit('close')
    },
    addUser (userList) {
      this.userList = userList
    },
    async save(){
      if(this.node.stepType === "SEND_WEBHOOK"){
        if(this.webhookData.webhookType === 'defaultRequest'){
          this.inputs.defaultRequest = this.webhookData.defaultData
          delete this.inputs.customRequest
        }
        else if(this.webhookData.webhookType === 'customRequest'){
          let bodyType = this.webhookData.customData.bodyType
          this.inputs.customRequest = this.webhookData.customData
          this.inputs.customRequest.body = {
            [bodyType]: this.webhookData.customData.body[bodyType]
          }
          delete this.inputs.defaultRequest
        }
      } else {
        let userIds = ""
        this.userList.forEach((u, index) => {
          if(index === this.userList.length - 1){
            userIds += u.userId
          }else {
            userIds += u.userId + ','
          }
        })
        this.noticeData.userIds = userIds
        this.inputs.row = this.formData

        for (const key in this.noticeData) {
            this.inputs[key] = this.noticeData[key]
        }
      }

      this.$emit('close')
      this.$emit('setProperties', {
        inputs: this.inputs
      })
    },
    async handleSelectWorksheet(worksheetId){
      let result = await getWorksheetDetail(worksheetId)
      if(result){
            if('config' in result){
                this.fieldList = result.fields;
            }
        }
    }
  },
  computed:{
    appId(){
      return this.$route.params.appId
    },
    id(){
        return this.$route.params.id
    }
  }
}
</script>

<style scoped>
.form_item{
  margin-top: 10px;
  margin-bottom: 20px;
}
.form_item_title{
  /* font-size: 18px; */
  /* font-weight: bold; */
  color: #000000;
  margin: 15px 0 5px 0;
}
</style>